package com.laker.autotest.page.csdn;


import com.laker.autotest.core.BasePage;
import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.options.AriaRole;
import com.microsoft.playwright.options.LoadState;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * <p>
 * 遍历CSDN用户主页的文章
 * </p>
 */
@Slf4j
public class CsdnUserHomePage extends BasePage {
    private static final String URL = "https://blog.csdn.net/abu935009066";
    private final String blogTitle = "blog-list-box-top";

    public CsdnUserHomePage(Page page) {
        super(page);
    }

    @Override
    protected String pageUrl() {
        return URL;
    }

    public void list() {
        Locator blogTitleLocator = getComponentByClassName(blogTitle);
        List<Locator> all = blogTitleLocator.all();
        all.forEach(locator -> {
            // 判断是否存在passportbox 即登录框，有的话直接关闭
            closePassPortBox(page);
            String text = getComponentText(locator);
            log.info("title: {}", text);
            Page detailPage = page.waitForPopup(locator::click);
            detailPage.waitForLoadState(LoadState.DOMCONTENTLOADED);
            closePassPortBox(detailPage);
            clickPreCode(detailPage);
            wheelAndWait(detailPage);
            clickPreCode(detailPage);
            wheelAndWait(detailPage);
            detailPage.close();
        });
    }

    private static void wheelAndWait(Page detailPage) {
        // 模拟鼠标滚轮向下滚动 1000px
        detailPage.mouse().wheel(0, 1000);
        // 等待一段时间，以便观察滚动效果
        detailPage.waitForTimeout(2000);
    }

    private void closePassPortBox(Page page) {
        Locator passportbox = page.locator("#passportbox").getByRole(AriaRole.IMG);
        if (passportbox.isVisible()) {
            passportbox.click();
        }
    }

    private void clickPreCode(Page page) {
        Locator precodes = page.locator("css=.look-more-preCode.contentImg-no-view");
        List<Locator> all = precodes.all();
        all.forEach((precode) -> {
            if (precode.isVisible()) {
                precode.click();
            }
        });
    }

}